package com.pxxy.lawconsult.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.pxxy.lawconsult.bean.User;
import com.pxxy.lawconsult.constant.DBConstant;
import com.pxxy.lawconsult.utils.DBUtils;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;

@WebServlet("/GetUserPhotoServlet")
public class GetUserPhotoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String GETUSERPHOTO = "getUserPhoto";//Json获取头像:key
	private static final String GETUSERPHOTO_SUCCESS = "success";//json获取头像:value,成功
	private static final String GETUSERPHOTO_FAILURE = "failure";//json获取头像:value,失败
	private static final String GETUSERPHOTO_SERVER = "serverError";//json获取头像:value,服务器错误

	private static final String GETUSERPHOTO_DATA = "data";//json数据:key
	public Map<String, String> map = null;

	public GetUserPhotoServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tel = request.getParameter(User.TEL);
		
		PrintWriter out = response.getWriter();
		//创建Gson对象
		Gson gson = new Gson();
		map = new HashMap<>();
		//判断是否为空
		if (tel == null || tel.equals("")) {
			map.put(GETUSERPHOTO, GETUSERPHOTO_FAILURE);
			out.write(gson.toJson(map));
			return;
		}

		try {
			ResultSet rs = DBUtils.query(DBConstant.TB_USER_TABLE, DBConstant.USER_TABLE_TEL, tel);
			if(rs.next()) {
				String image = rs.getString(DBConstant.USER_TABLE_IMAGE);
				//设置请求成功
				map.put(GETUSERPHOTO, GETUSERPHOTO_SUCCESS);
				//放置图片url
				map.put(GETUSERPHOTO_DATA,image);
			}else {
				//设置请求失败
				map.put(GETUSERPHOTO, GETUSERPHOTO_FAILURE);
			}
		}catch (Exception e) {
			//设置服务器错误
			map.put(GETUSERPHOTO, GETUSERPHOTO_SERVER);
			e.printStackTrace();
		}finally {
			String getUserPhotoJson = gson.toJson(map);
			out.println(getUserPhotoJson);
			//关闭
			DBUtils.close();
			out.close();
		}
	}

}
